import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_dialog_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'binding_terminal/binding_terminal_view_model.dart';


/// 设置设备音量弹窗
class SetTerminalVolumeDialog extends StatefulWidget {

  final String onOff;
  final String hsn;
  final int volume;
  final Function(int volume) changeVolume;

  const SetTerminalVolumeDialog({Key key, this.onOff, this.hsn,
    this.volume, this.changeVolume}) : super(key: key);

  @override
  _SetTerminalVolumeDialogState createState() =>
      _SetTerminalVolumeDialogState();

  ///跳转方法
  static Future<int> navigatorPushDialog(BuildContext context,
      String onOff, String hsn, int volume, {Function(int volume) changeVolume}) {
    return VgDialogUtils.showCommonBottomDialog<int>(
      context: context,
      enableDrag: false,
      child: SetTerminalVolumeDialog(
        onOff:onOff,
        hsn:hsn,
        volume:volume,
        changeVolume:changeVolume,
      ),
    );
  }

}

class _SetTerminalVolumeDialogState extends BaseState<SetTerminalVolumeDialog>{
  BindingTerminalViewModel _viewModel;
  int _volume;
  bool _pressFlag = false;
  @override
  void initState() {
    super.initState();
    _viewModel = BindingTerminalViewModel(this);
    if("01" == widget?.onOff){
      _volume = 0;
    }else{
      _volume = widget?.volume??50;
    }
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
      child: Container(
        decoration: BoxDecoration(
            color: ThemeRepository.getInstance().getCardBgColor_21263C()),
        padding: EdgeInsets.only(left: 15, top: 15, bottom: 58),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Container(
              alignment: Alignment.centerLeft,
              child: Row(
                children: [
                  Text(
                    "音量设置",
                    style: TextStyle(
                        fontSize: 17,
                        fontWeight: FontWeight.bold,
                        color: ThemeRepository.getInstance().getTextMainColor_D0E0F7()),
                  ),
                  Spacer(),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: (){
                      RouterUtils.pop(context);
                    },
                    child: Container(
                      padding: EdgeInsets.only(left:50, right: 22),
                      child: Image.asset(
                        "images/icon_close_volume_dialog.png",
                        width: 15,
                        height: 15,
                      ),
                    ),
                  )
                ],
              ),
            ),
            SizedBox(height: 25,),
            // Row(
            //   mainAxisSize: MainAxisSize.max,
            //   children: [
            //     Image.asset(
            //       "images/icon_voice_detail.png",
            //       width: 25,
            //       height: 25,
            //     ),
            //     SizedBox(width: 14,),
            //     Expanded(
            //       child: SeekBar(
            //         progressColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            //         backgroundColor: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
            //         progresseight: 4,
            //         indicatorRadius: 10,
            //         value: _volume.toDouble(),
            //         onValueChanged: (value){
            //           setState(() {
            //             this._volume = value.value.floor();
            //           });
            //         },
            //         onChangeEnd: (value){
            //           _viewModel.changeVolume(context, widget?.hsn,
            //               _volume>0?"00":"01", _volume, needPop: true);
            //         },
            //       ),
            //     ),
            //     SizedBox(width: 14,),
            //     Text(
            //       "${_volume??50}%",
            //       style: TextStyle(
            //           fontSize: 15,
            //           color: ThemeRepository.getInstance().getTextMainColor_D0E0F7()),
            //     ),
            //   ],
            // ),
            // SizedBox(height: 25,),
            Row(
              mainAxisSize: MainAxisSize.max,
              children: [
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onPanEnd: (detail){
                    setState(() {_pressFlag = false;});
                  },
                  onTapUp: (detail){
                    setState(() {_pressFlag = false;});
                  },
                  onTap: (){
                    setState(() {
                      _pressFlag = true;
                      _volume = 0;
                      if(widget?.changeVolume != null){
                        RouterUtils.pop(context);
                        widget?.changeVolume?.call(_volume);
                      }else{
                        _viewModel.changeVolume(context, widget?.hsn,
                            _volume>0?"00":"01", _volume, needPop: true);
                      }
                    });
                  },
                  onTapDown: (detail){
                    setState(() {_pressFlag = true;});
                  },
                  child: Image.asset(
                    _pressFlag?"images/icon_voice_detail.png":"images/icon_mute_grey.png",
                    width: 25,
                    height: 25,
                  ),
                ),
                SizedBox(width: 20,),
                Expanded(
                  child: SliderTheme(
                    data: SliderThemeData(
                        overlayShape: SliderComponentShape.noOverlay,
                        thumbShape: RingThumbShape(15, 25, 12.5, 10),
                        trackHeight: 4,
                        trackShape: CustomRoundedRectSliderTrackShape(),
                        inactiveTickMarkColor: Colors.transparent,
                        activeTickMarkColor: Colors.transparent,
                        inactiveTrackColor: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                        activeTrackColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                        valueIndicatorColor: Colors.transparent),
                    child: Slider(
                      min: 0.0,
                      max: 100,
                      value: _volume.toDouble(),
                      divisions: 1000,
                      onChanged: (value) {
                        setState(() {
                          this._volume = value.ceil();
                        });
                      },
                      onChangeEnd: (value){
                        if(widget?.changeVolume != null){
                          RouterUtils.pop(context);
                          widget?.changeVolume?.call(_volume);
                        }else{
                          _viewModel.changeVolume(context, widget?.hsn,
                              _volume>0?"00":"01", _volume, needPop: true);
                        }
                      },
                    ),
                  ),
                ),
                SizedBox(width: 5,),
                Container(
                  width: 55,
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "${_volume??50}%",
                    style: TextStyle(
                        fontSize: 15,
                        color: ThemeRepository.getInstance().getTextMainColor_D0E0F7()),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

///游标形状
class RingThumbShape extends SliderComponentShape {

  final double width;
  final double height;
  final double ringRadius;
  final double indicatorRadius;
  final Color ringColor;
  final Color indicatorColor;
  RingThumbShape(this.width, this.height, this.ringRadius, this.indicatorRadius,
  {this.ringColor, this.indicatorColor});


  @override
  Size getPreferredSize(bool isEnabled, bool isDiscrete) {
    return Size(width, height);
  }

  @override
  void paint(PaintingContext context,
      Offset center,
      {Animation<double> activationAnimation,
        Animation<double> enableAnimation,
        bool isDiscrete,
        TextPainter labelPainter,
        RenderBox parentBox,
        SliderThemeData sliderTheme,
        TextDirection textDirection,
        double value,
        double textScaleFactor,
        Size sizeWithOverflow}) {
    Canvas canvas = context.canvas;
    Paint indicatorPaint = new Paint()
      ..style = PaintingStyle.fill
      ..color = indicatorColor??Color(0xff1890ff);
    Paint ringPaint = new Paint()
      ..style = PaintingStyle.fill
      ..color = ringColor??Colors.white;
    canvas.drawCircle(Offset(center.dx, center.dy),
        8, ringPaint);
    canvas.drawCircle(Offset(center.dx, center.dy),
        6, indicatorPaint);
  }


}

///自定义trackshape
class CustomRoundedRectSliderTrackShape extends SliderTrackShape with BaseSliderTrackShape {
  /// Create a slider track that draws two rectangles with rounded outer edges.
  final LinearGradient activeGradient;
  const CustomRoundedRectSliderTrackShape({this.activeGradient});

  @override
  void paint(
      PaintingContext context,
      Offset offset, {
        @required RenderBox parentBox,
        @required SliderThemeData sliderTheme,
        @required Animation<double> enableAnimation,
        @required TextDirection textDirection,
        @required Offset thumbCenter,
        bool isDiscrete = false,
        bool isEnabled = false,
      }) {
    assert(context != null);
    assert(offset != null);
    assert(parentBox != null);
    assert(sliderTheme != null);
    assert(sliderTheme.disabledActiveTrackColor != null);
    assert(sliderTheme.disabledInactiveTrackColor != null);
    assert(sliderTheme.activeTrackColor != null);
    assert(sliderTheme.inactiveTrackColor != null);
    assert(sliderTheme.thumbShape != null);
    assert(enableAnimation != null);
    assert(textDirection != null);
    assert(thumbCenter != null);
    // If the slider [SliderThemeData.trackHeight] is less than or equal to 0,
    // then it makes no difference whether the track is painted or not,
    // therefore the painting  can be a no-op.
    if (sliderTheme.trackHeight <= 0) {
      return;
    }

    // Assign the track segment paints, which are leading: active and
    // trailing: inactive.
    final ColorTween activeTrackColorTween = ColorTween(begin: sliderTheme.disabledActiveTrackColor, end: sliderTheme.activeTrackColor);
    final ColorTween inactiveTrackColorTween = ColorTween(begin: sliderTheme.disabledInactiveTrackColor, end: sliderTheme.inactiveTrackColor);
    final Rect trackRect = getPreferredRect(
      parentBox: parentBox,
      offset: offset,
      sliderTheme: sliderTheme,
      isEnabled: isEnabled,
      isDiscrete: isDiscrete,
    );

    Paint activePaint;
    if(activeGradient != null){
      activePaint = new Paint()..shader = activeGradient.createShader(trackRect);
    }else{
      activePaint = Paint()..color = activeTrackColorTween.evaluate(enableAnimation);
    }

    final Paint inactivePaint = Paint()..color = inactiveTrackColorTween.evaluate(enableAnimation);
    Paint leftTrackPaint;
    Paint rightTrackPaint;
    switch (textDirection) {
      case TextDirection.ltr:
        leftTrackPaint = activePaint;
        rightTrackPaint = inactivePaint;
        break;
      case TextDirection.rtl:
        leftTrackPaint = inactivePaint;
        rightTrackPaint = activePaint;
        break;
    }



    final Radius trackRadius = Radius.circular(trackRect.height / 2);
    final Radius activeTrackRadius = Radius.circular(trackRect.height / 2 + 1);

    context.canvas.drawRRect(
      RRect.fromLTRBAndCorners(
        trackRect.left,
        (textDirection == TextDirection.ltr) ? trackRect.top: trackRect.top,
        thumbCenter.dx,
        (textDirection == TextDirection.ltr) ? trackRect.bottom : trackRect.bottom,
        topLeft: (textDirection == TextDirection.ltr) ? activeTrackRadius : trackRadius,
        bottomLeft: (textDirection == TextDirection.ltr) ? activeTrackRadius: trackRadius,
      ),
      leftTrackPaint,
    );
    context.canvas.drawRRect(
      RRect.fromLTRBAndCorners(
        thumbCenter.dx,
        (textDirection == TextDirection.rtl) ? trackRect.top : trackRect.top,
        trackRect.right,
        (textDirection == TextDirection.rtl) ? trackRect.bottom : trackRect.bottom,
        topRight: (textDirection == TextDirection.rtl) ? activeTrackRadius : trackRadius,
        bottomRight: (textDirection == TextDirection.rtl) ? activeTrackRadius : trackRadius,
      ),
      rightTrackPaint,
    );
  }
}
